"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 重建过程中，停止主机数据库，备机重建失败
Create At   : 2020-6-28
Owner       : @peilinqian
Description :
    1、重建备机
    2、同时kill主机数据库
    3、备机重建失败日志断言
    4、重启主机
    5、重建备机成功
Expect      :
History     :
    Modified by @wan005 2021/9/27: 优化期望，优化打印
"""

import os
import time
import unittest

from testcase.utils.ComThread import *
from testcase.utils.Common import *
from testcase.utils.CommonSH import *
from testcase.utils.CommonSH import *
from yat.test import Node
from yat.test import macro


class MyTest(unittest.TestCase):
    primary_sh = CommonSH('PrimaryDbUser')
    standby1_sh = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case016.py start------------')
        self.DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
        self.rootNode = Node(node='PrimaryRoot')
        self.dbUserNode = Node(node='PrimaryDbUser')
        self.standbyrootNode = Node(node='Standby1Root')
        self.standbydbUserNode = Node(node='Standby1DbUser')
        self.com = Common()
        self.Constant = Constant()

    def test_main(self):
        text = "重建备机"
        self.log.info(text)
        buildthread = ComThread(self.standby1_sh.executeGsctl,
                                args=('build', self.Constant.REBUILD_SUCCESS_MSG, '-b full',))
        buildthread.setDaemon(True)
        buildthread.start()

        time.sleep(5)

        text = "kill掉主机进程"
        self.log.info(text)
        msg = self.com.kill_pid(self.rootNode, 9)
        self.assertEqual(msg, '')

        text = "等待备机重建进程执行完成"
        self.log.info(text)
        buildthread.join(60*20)

        text = "断言备机重建失败"
        self.log.info(text)
        build_result = buildthread.get_result()
        self.log.info(build_result)
        self.assertFalse(build_result)
        self.log.info("build failed")

        time.sleep(5)

        text = "重启主机"
        self.log.info(text)
        startmsg = self.primary_sh.startDbCluster()
        self.log.info(startmsg)

        text = "重建备机失败，因为证书文件损坏导致重建不成功处理异常"
        self.log.info(text)
        result = self.standby1_sh.build_fail_scp_crtfile()
        self.log.info(result)
        self.assertTrue(result)
        db_status = self.primary_sh.getDbClusterStatus('detail')
        self.log.info(db_status)
        self.assertTrue("Degraded" in db_status or "Normal" in db_status)

    def tearDown(self):
        db_status = self.primary_sh.getDbClusterStatus('status')
        self.log.info(db_status)
        if not db_status:
            self.log.info('*****start cp server.crt files*****')
            find_cmd = f"find {os.path.dirname(macro.DB_INSTANCE_PATH)} -type d -name 'sslcert'"
            self.log.info(find_cmd)
            om_path = self.standbyrootNode.sh(find_cmd).result()
            self.log.info(om_path)
            edit_cmd = f'''cd {om_path.strip()}/om/;
                        cp server.key.rand server.key.cipher server.key server.crt {macro.DB_INSTANCE_PATH}'''
            self.standbydbUserNode.sh(edit_cmd)
            self.log.info(edit_cmd)
            msg = self.standby1_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG, '-b full')
            self.assertTrue(msg)
